﻿using System;
using System.Data;
using System.Windows.Forms;
using HRM.HRMServiceProxy;
using WeifenLuo.WinFormsUI.Docking;
using System.Collections.Generic;
using System.IO;
using HRM.BusinessLogic;
using HRM.Controller;

namespace HRM
{
    public partial class frmHospitalList : FormBase
    {
        int pageSize = UIParamater.pageSize;
        int currPage = 0;
        int itemCount = 0;
        int totalPage = 0;
        int _HospitalID = 0;
        HospitalClient _wcfHospital;
        RoleRightInfo listRole;
        bool _IsSearch = false;
        string _HospitalCode;
        string _RegionCode = "";
        public string HospitalCode
        {
            get { return _HospitalCode; }
            set { _HospitalCode = value; }
        }
        string _HospitalName = "";
        public string HospitalName
        {
            get { return _HospitalName; }
            set { _HospitalName = value; }
        }

        string _HospitalRegionCode = "";
        public string HospitalRegionCode
        {
            get { return _HospitalRegionCode; }
            set { _HospitalRegionCode = value; }
        }


        public override void Show_Form()
        {
            this.Show();
        }

        public frmHospitalList()
        {
            InitializeComponent();
            Init_Control();
        }

        public frmHospitalList(bool IsSearch = false)
        {
            InitializeComponent();
            //
            _IsSearch = IsSearch;
            Init_Control();
            if (cboRegionCode.ComboBox.Items.Count > 1)
            {
                cboRegionCode.SelectedItem = 1;
                //loadList();
            }
        }

        protected override void Init_Control()
        {
            //   LoadLanguage();
            _wcfHospital = Service.Hospital();
            listRole = UIParamater.Quyen_TonGiao;
            UISetting.LoadRegion(ref cboRegionCode);
            if (!listRole._create)
                btnNew.Enabled = false;
            if (!listRole._delete)
                btnDel.Enabled = false;
            if (!listRole.Update)
            {
                this.btnEdit.Image = global::HRM.Properties.Resources.app;
                btnEdit.Text = "xem";
            }
            

            btnExcel.Enabled = Program.strUserName.ToUpper() == "VVTUY"; //vvtuy đc update
            this.KeyPreview = true;
        }

        void LoadLanguage()
        {
            if (this.Tag != null)
                this.Text = this.TabText = UpdateUI.GetString(this.Tag.ToString());
            UpdateUI.Load_ToolStrip(ref toolStrip1);
            UpdateUI.Load_ContextMenuStrip(ref mnuPopup);
        }
        private void loadList()
        {
            FormGlobals.App_ProgressShow(delegate (){
            DataTable dt = _wcfHospital.Hospital_GetList(out itemCount, txtName.Text, _RegionCode, currPage, pageSize).Tables[0];
            totalPage = itemCount % pageSize > 0 ? (itemCount / pageSize) + 1 : (itemCount / pageSize);
            if (totalPage == 0)
                lblPageIndex.Text = "0" + "/" + totalPage.ToString();
            else
                lblPageIndex.Text = (currPage + 1).ToString() + "/" + totalPage.ToString();

            dgvList.DataSource = dt;
            dgvList.Columns["Hospital_ID"].Visible = false;
            dgvList.Columns["ROWNUMBER"].HeaderText = "STT";
            dgvList.Columns["ROWNUMBER"].Width = 70;
            dgvList.Columns["Hospital_Name"].HeaderText = "Tên bện viện";
            dgvList.Columns["Hospital_Name"].Width = 250;
            dgvList.Columns["Hospital_Code"].HeaderText = "Mã bệnh viện";
            dgvList.Columns["Hospital_Code"].Width = 120;
            dgvList.Columns["Hospital_RegionCode"].HeaderText = "Mã tỉnh thành";
            dgvList.Columns["Hospital_RegionCode"].Width = 150;
            //dgvList.Columns["Hospital_IsUse"].HeaderText = "Sử dụng";
            //dgvList.Columns["Hospital_IsUse"].Width = 120;
            //dgvList.Columns["Hospital_Level"].HeaderText = "Tuyến bệnh viện";
            //dgvList.Columns["Hospital_IsUse"].Width = 150;
            },"Loading");
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            if (!listRole.Create)
            {
                MessageBox.Show(UpdateUI.GetString("khongcoquyenthemmoi"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            Form f = new frmHospitalInfo(0, listRole);
            if (f.ShowDialog(this) == DialogResult.OK)
            {
                loadList();
            }
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (dgvList.SelectedRows.Count > 0)
            {
                if (listRole.Update || listRole.View)
                {

                    _HospitalID = Convert.ToInt32(dgvList.CurrentRow.Cells["Hospital_ID"].Value);
                    Form f = new frmHospitalInfo(_HospitalID, listRole);
                    if (f.ShowDialog(this) == DialogResult.OK)
                    {
                        loadList();
                    }
                }
                else
                    MessageBox.Show(UpdateUI.GetString("khongcoquyenxem"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            if (dgvList.SelectedRows.Count > 0)
            {
                if (!listRole.Delete)
                {
                    MessageBox.Show(UpdateUI.GetString("khongcoquyenxoa"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                _HospitalID = Convert.ToInt32(dgvList.CurrentRow.Cells["Hospital_ID"].Value);
                if (MessageBox.Show(UpdateUI.GetString("bancochacchanxoa"), UIParamater.TitleProject, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    if (_wcfHospital.Hospital_Delete(_HospitalID))
                    {
                        Program.taskbarNotifier.Show(UIParamater.TitleProject, UpdateUI.GetString("xoathanhcong"), UIParamater.TIME_MOVE_UP, UIParamater.TIME_SHOW, UIParamater.TIME_MOVE_DOWN);
                        loadList();
                    }
                    else
                    {
                        MessageBox.Show(UpdateUI.GetString("xoakhongthanhcong"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
        }

        private void btnFisrt_Click(object sender, EventArgs e)
        {
            currPage = 0;
            loadList();

        }

        private void btnPrevious_Click(object sender, EventArgs e)
        {

            if (currPage > 0)
                currPage--;
            loadList();
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            if (totalPage > 0 && currPage < totalPage - 1)
                currPage++;
            loadList();

        }

        private void btnLast_Click(object sender, EventArgs e)
        {
            if (totalPage > 0)
                currPage = totalPage - 1;
            loadList();
        }

        private void dgvList_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvList.SelectedRows.Count > 0)
            {
                if (!_IsSearch)
                {
                    btnEdit_Click(null, null);
                }
                else
                {
                    _HospitalCode = dgvList.CurrentRow.Cells["Hospital_Code"].Value.ToString();
                    _HospitalName = dgvList.CurrentRow.Cells["Hospital_Name"].Value.ToString();
                    _HospitalRegionCode = dgvList.CurrentRow.Cells["Hospital_RegionCode"].Value.ToString();
                    this.DialogResult = DialogResult.OK;
                }
            }
        }

        private void frmHospitalList_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Escape:
                    this.Dispose();
                    this.Close();
                    break;
                case Keys.F2:
                    btnNew_Click(null, null);
                    break;
                case Keys.F3:
                    btnEdit_Click(null, null);
                    break;
                case Keys.Delete:
                    btnDel_Click(null, null);
                    break;
            }
        }

        private void btnNewPopUp_Click(object sender, EventArgs e)
        {
            btnNew_Click(null, null);
        }

        private void btnEditPopUp_Click(object sender, EventArgs e)
        {
            btnEdit_Click(null, null);
        }

        private void btnDelPopUp_Click(object sender, EventArgs e)
        {
            btnDel_Click(null, null);
        }

        private void dgvList_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (dgvList.SelectedRows.Count > 0)
                {
                    mnuPopup.Enabled = true;
                    btnNewPopUp.Enabled = true;
                    btnEditPopUp.Enabled = true;
                    btnDelPopUp.Enabled = true;
                }
            }
        }

        private void frmHospitalList_Activated(object sender, EventArgs e)
        {
            if (dgvList.Columns.Count > 0)
            {
                dgvList.Columns["Hospital_Name"].HeaderText = "Tên tỉnh thành";
                dgvList.Columns["Hospital_Code"].HeaderText = "Mã bệnh viện";
            }
        }

        private void frmHospitalList_FormClosing(object sender, FormClosingEventArgs e)
        {
            _wcfHospital.Close();
        }

        private void txtName_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                btnSearch_Click(null, null);
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            currPage = 0;
            loadList();
        }

        private void cboRegionCode_SelectedIndexChanged(object sender, EventArgs e)
        {
            //if (!this.IsLoading)
            if (cboRegionCode.ComboBox.SelectedValue != null)
            {
                _RegionCode = cboRegionCode.ComboBox.SelectedValue.ToString();
                loadList();
            }

            //
            
        }

        private void btnExcel_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "Excel file (*.xls)|*.xls";

            if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
            {
               
                   InputData(openFileDialog1.FileName);
               
            }
        }

        private void InputData(string FileName)
        {
            int row = 0;
            string col = "";
            List<HospitalInfo> lstInfo = new List<HospitalInfo>();
            try
            {
                DataTable dt = null;
                dt = ExcelHelper.Excel_GetData(FileName, true, 0, false);
                HospitalInfo HospitalInfo;
                
                foreach (DataRow dr in dt.Rows)
                {
                    row++;
                    HospitalInfo = new HospitalInfo();
                    col = "ma_bv";
                    if (dr[col].ToString().Trim().Length == 0)
                    {
                        MessageBox.Show("Lỗi xảy ra: \nDòng: " + (row + 1).ToString() + "\nMã bệnh viện chưa nhập, hãy nhập lại trong file Excel!", "Thông báo", MessageBoxButtons.OK);
                        return;
                    }
                    else
                        HospitalInfo.Code = Convert.ToString(dr[col]).Trim();
                    col = "ten_bv";
                    if (dr[col].ToString().Trim().Length == 0)
                    {
                        MessageBox.Show("Lỗi xảy ra: \nDòng: " + (row + 1).ToString() + "\nTên bệnh viện chưa nhập, hãy nhập lại trong file Excel!", "Thông báo", MessageBoxButtons.OK);
                        return;
                    }
                    else
                        HospitalInfo.Name = dr[col].ToString().Trim();
                    col = "ma_tinh";
                    if (dr[col].ToString().Trim().Length == 0)
                    {
                        MessageBox.Show("Lỗi xảy ra: \nDòng: " + (row + 1).ToString() + "\nMã tỉnh thành chưa nhập, hãy nhập lại trong file Excel!", "Thông báo", MessageBoxButtons.OK);
                        return;
                    }
                    else
                        HospitalInfo.RegionCode = dr[col].ToString().Trim();
                    col = "khongsd";
                    HospitalInfo.IsUse = dr[col].ToString().Trim() == "" ? "0" : dr[col].ToString().Trim();
                    col = "tuyen_bv";
                    HospitalInfo.Level = dr[col].ToString().Trim();
                    lstInfo.Add(HospitalInfo);
                }
                int i = 0;
                FormGlobals.App_ProgressShow(delegate()
               {
                foreach (HospitalInfo item in lstInfo)
                {
                    Hospital_Controller.Instance().Hospital_Import(item.Code,UnicodeConvert.TCVN3ToUnicode(item.Name), item.RegionCode, item.IsUse, item.Level);
                    i++;
                }
               }, "Đang cập nhật dữ liệu...");
                string strMessage = "Cập nhật thành công " + i.ToString() + " dòng!";
                MessageBox.Show(strMessage, "Thông báo", MessageBoxButtons.OK);
                loadList();
            }
            catch (Exception ex)
            {
                lstInfo.Clear();
                MessageBox.Show("Lỗi xảy ra: \nDòng: " + (row + 1).ToString() + "\nCột: " + col + "\n" + ex.Message, "Thông báo", MessageBoxButtons.OK);
            }

        }
    }
}

